package org.csu.mypetstore.service;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.persistence.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

@Service
public class AccountService {

    @Autowired
    private AccountMapper accountMapper;

    public Account getAccountByUsernameAndPassword(Account account){
        return accountMapper.getAccountByUsernameAndPassword(account);
    }

    public void insertAccount(Account account) {
        accountMapper.insertAccount(account);
    }

    public Account getAccountByUsername(String username) {
        return accountMapper.getAccountByUsername(username);
    }

    public void updateAccount(Account account) {
        accountMapper.updateAccount(account);
    }

    public ArrayList<Account> getAccountList() {
        return accountMapper.getAccountList();
    }

    public void deleteAccount(String username) {
        accountMapper.deleteAccount(username);
    }

    public void recoverAccount(String username) {
        accountMapper.recoverAccount(username);
    }

    public void resetPassword(String username) {
        accountMapper.resetPassword(username);
    }

    private String code="";
    /**
     * 发送时间
     */
    private Date sendTime;

    public String getCode(String sender, JavaMailSenderImpl mailSender, String receiver) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("验证码");//设置邮件标题

        String str="0123456789";
        Random random=new Random();
        StringBuffer s =new StringBuffer();
        for(int i=0;i<6;i++){
            int number=random.nextInt(10);
            s.append(str.charAt(number));
        }

        code = s.toString();
        sendTime = new Date();
        message.setText("尊敬的用户,您好:\n"
                + "\n本次请求的邮件验证码为:" + code + "（请勿泄露此验证码）\n"
                + "\n如非本人操作，请忽略该邮件。\n(这是一封自动发送的邮件，请不要直接回复）");    //设置邮件正文
        message.setFrom(sender);//发件人
        message.setTo(receiver);//收件人
        mailSender.send(message);//发送邮件
        return code;
    }

    public Account getAccountByEmail(String receiver) {
        return accountMapper.getAccountByEmail(receiver);
    }

    public Account getAdminAccountByUsernameAndPassword(Account account) {
        return accountMapper.getAdminAccountByUsernameAndPassword(account);
    }

    public Account getAdminAccountByEmail(String receiver) {
        return accountMapper.getAdminAccountByEmail(receiver);
    }
}
